import { Box, useCall, useSimpleMemo, useToggle } from '@/components';
import { forkHandler, nextLoop, pathJoin } from '@/utils';
import { Button, message, Space, Spin, Steps } from 'antd';
import React, { useRef } from 'react';
import { Route, Switch, useRouteMatch } from 'react-router-dom';
import BasicConfig from './components/BasicConfig';
import BenefitDataConfig from './components/BenefitDataConfig';
import BenefitDescConfig from './components/BenefitDescConfig';
import DefinitionContext, { useDefinitionContext } from './components/Context';
import ShowContentConfig from './components/ShowContentConfig';
import styles from './index.less';

const steps = ['', 'benefitData', 'benefitDesc', 'showContent'];

function useStep(parentPath) {
  const step = useRouteMatch(pathJoin(parentPath, '/:current?')).params.current ?? '';
  return steps.indexOf(step);
}

function AddPage({ match, location, history }) {
  const step = useStep(match.path);
  const [definitionData, setData, loading] = useDefinitionContext();
  const hasShowContent = String(definitionData?.productDefineList?.[0]?.productType) === '1';
  const isLastStep = step === (hasShowContent ? 3 : 2);
  const nextRoute = `${steps[step + 1] ?? ''}${location.search}`;
  const prevRoute = `${steps[step - 1] || './'}${location.search}`;

  const currentRef = useRef();

  const [pageLoading, toggle] = useToggle(loading);

  const onPrev = useCall(() => {
    if (step > 0) {
      history.replace(prevRoute);
    } else {
      history.goBack();
    }
  });
  const onSave = useCall(
    forkHandler(
      () => {
        if (loading || pageLoading) return false;
        if (!pageLoading) toggle();
        return nextLoop(true);
      },
      () => currentRef.current?.onSave?.() ?? true,
      toggle,
      true,
    ).catch(toggle),
  );
  const onSaveBack = useCall(
    forkHandler(
      onSave,
      () => {
        message.success('保存成功');
        history.goBack();
      },
      true,
    ),
  );

  const onSaveNext = useCall(
    forkHandler(
      onSave,
      () => {
        if (isLastStep) {
          message.success('保存成功');
          history.goBack();
        } else {
          history.replace(nextRoute);
        }
      },
      true,
    ),
  );

  return (
    <>
      <Box px={3} mx='auto' my={2} className={styles.steps}>
        <Steps current={step}>
          <Steps.Step title='选择产品' />
          <Steps.Step title='利益演示' />
          <Steps.Step title='利益责任描述' />
          {hasShowContent && <Steps.Step title='阅读文件/文本' />}
        </Steps>
      </Box>

      <DefinitionContext.Provider value={useSimpleMemo({ definitionData, setData })}>
        <Spin spinning={pageLoading}>
          <Switch>
            <Route path={pathJoin(match.path, '/benefitData')}>
              <BenefitDataConfig ref={currentRef} />
            </Route>
            <Route path={pathJoin(match.path, '/benefitDesc')}>
              <BenefitDescConfig ref={currentRef} />
            </Route>
            <Route path={pathJoin(match.path, '/showContent')}>
              <ShowContentConfig ref={currentRef} />
            </Route>
            <Route>
              <BasicConfig ref={currentRef} />
            </Route>
          </Switch>
        </Spin>
      </DefinitionContext.Provider>

      <Box flex jus='center' py={3} className='form-page-btn'>
        <Space size='large'>
          <Button onClick={onPrev}>{step > 0 ? '上一步' : '取消'}</Button>
          {!isLastStep && <Button onClick={onSaveBack}>保存</Button>}
          <Button onClick={onSaveNext} type='primary'>
            {isLastStep ? '完成配置' : '下一步'}
          </Button>
        </Space>
      </Box>
    </>
  );
}

export default AddPage;
